package com.think.oauth.user.security;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import com.think.oauth.user.exception.CustomWebResponseExceptionTranslator;
import com.think.oauth.user.security.token.CustomTokenEnhancer;
import com.think.oauth.user.security.token.ILabCustomTokenGranter;
import com.think.oauth.user.security.token.ILabTokenCustomTokenGranter;
import com.think.oauth.user.security.token.PhoneSmsCustomTokenGranter;
import com.think.oauth.user.security.token.QHCasTicketCustomTokenGranter;
import com.think.oauth.user.security.token.WxCodeWebCustomTokenGranter;
import com.think.oauth.user.service.CustomClientDetailService;
import com.think.oauth.user.service.CustomUserDetailsService;


@Configuration
@Order(-50)
@EnableAuthorizationServer
public class CustomAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

	@Resource
    private DataSource dataSource;
//
//    @Bean // 声明TokenStore实现
//    public TokenStore tokenStore() {
//        return new JdbcTokenStore(dataSource);
//    }
    
	@Autowired
    public TokenStore jwtTokenStore;
	
    @Autowired
    private TokenEnhancer jwtTokenEnhancer;
    
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;

    @Bean // 声明 ClientDetails实现
    public ClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    }
    
    @Autowired
    private CustomUserDetailsService userDetailsService;
    
    @Autowired
    private CustomClientDetailService clientDetailService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
	 private RedisTemplate redisTemplate;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    	clients.jdbc(dataSource);
    }

    @Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    	 security.allowFormAuthenticationForClients().tokenKeyAccess("isAuthenticated()")
         .checkTokenAccess("permitAll()").passwordEncoder(passwordEncoder);
	}
    
    @Autowired
    PasswordEncoder passwordEncoder;

	@Override 
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
		endpoints.authenticationManager(authenticationManager);
        endpoints.userDetailsService(userDetailsService);
        endpoints.setClientDetailsService(clientDetails());
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setSupportRefreshToken(true); 
        tokenServices.setTokenStore(jwtTokenStore); 
        tokenServices.setAccessTokenValiditySeconds(3600*24*365);
        endpoints.tokenServices(tokenServices);
        endpoints.reuseRefreshTokens(true);        
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancerList = new ArrayList<>();
        enhancerList.add(jwtTokenEnhancer);
        enhancerList.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(enhancerList);
        tokenServices.setTokenEnhancer(enhancerChain);
        List<TokenGranter> tokenGranters = getTokenGranters(endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory());
        tokenGranters.add(endpoints.getTokenGranter());
        endpoints.tokenGranter(new CompositeTokenGranter(tokenGranters));
        endpoints.exceptionTranslator(new CustomWebResponseExceptionTranslator());
    }

    private List<TokenGranter> getTokenGranters(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        return new ArrayList<>(Arrays.asList(
                new PhoneSmsCustomTokenGranter(tokenServices, clientDetailsService, requestFactory, userDetailsService),
                new WxCodeWebCustomTokenGranter(tokenServices, clientDetailsService, requestFactory, userDetailsService),
                new ILabCustomTokenGranter(tokenServices, clientDetailsService, requestFactory, userDetailsService,redisTemplate),
                new ILabTokenCustomTokenGranter(tokenServices, clientDetailsService, requestFactory, userDetailsService),
                new QHCasTicketCustomTokenGranter(tokenServices, clientDetailsService, requestFactory, userDetailsService)
        ));
    }
}
